package com.aaa.security.aspect;

import com.aaa.security.annotation.HasPermission;
import com.aaa.security.exception.PermissionException;
import com.aaa.security.util.WebUtils;
import com.aaa.util.JwtUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;

/**
 * @program: qy158-cai-parent
 * @description:
 * @author: 闫克起
 * @create: 2023-02-23 15:19
 **/
@Aspect
@Component
public class PermissionAspect {
    @Pointcut(value = "@annotation(com.aaa.security.annotation.HasPermission)")
    public void pointcut(){}
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
         //获取方法对象。
        MethodSignature methodSignatur= (MethodSignature) joinPoint.getSignature();
        Method method = methodSignatur.getMethod();
        //获取方法上HasPermission
        HasPermission annotation = method.getAnnotation(HasPermission.class);
        if(annotation!=null){
            String permission = annotation.value();
            //在springmvc任意唯一获取request对象。
            HttpServletRequest request = WebUtils.getRequest();
            String token = request.getHeader("token");
            //解析token
            Map<String, Object> map = JwtUtil.getTokenChaim(token);
            List<String> authorities = (List<String>) map.get("authorities");
            if(!authorities.contains(permission)){
                throw new PermissionException("权限不足");
            }
        }
        return joinPoint.proceed();
    }
}
